package pl.wwysocki.gendok;

import java.lang.reflect.Method;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.odftoolkit.odfdom.doc.text.OdfTextUserFieldDecl;

public class FieldDecl
{
	private static final Log log = LogFactory.getLog(FieldDecl.class);
	private String name;
	private Object bean;
	private Method fieldGetter;
	private OdfTextUserFieldDecl element;

	public FieldDecl(String name, Method fieldGetter, Object bean)
	{
		super();
		this.name = name;
		this.fieldGetter = fieldGetter;
		this.bean = bean;
	}

	public boolean isListType()
	{
		return false;
	}

	public Method getFieldGetter()
	{
		return fieldGetter;
	}

	public void setFieldGetter(Method fieldGetter)
	{
		this.fieldGetter = fieldGetter;
	}

	public Object getBean()
	{
		return bean;
	}

	public void setBean(Object bean)
	{
		this.bean = bean;
	}

	public OdfTextUserFieldDecl getElement()
	{
		return element;
	}

	public void setElement(OdfTextUserFieldDecl element)
	{
		this.element = element;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public void show()
	{
		log.info("nazwa elementu: " + element.getTextNameAttribute());
		log.info("typ: obiekt");
		log.info("bean: " + bean);
		try
		{
			log.info("getter pola: " + (fieldGetter == null ? "brak gettera" : fieldGetter.getName()));
			if (fieldGetter != null)
			{
				Object obj = fieldGetter.invoke(bean, null);
				log.info("wartosc: " + (obj == null ? "null" : obj.toString()));
			}
		}
		catch (Exception e)
		{
			log.error(String.format("Blad pobrania wartosci z obiektu %s za pomoca gettera %s",
					bean.toString(), fieldGetter.getName()));
			e.printStackTrace();
		}
		log.info("------------------------");
	}

	public void storeValue()
	{
		log.info(String.format("store value %s", name));
		try
		{
			if (fieldGetter != null && bean != null)
			{
				Object obj = fieldGetter.invoke(bean, null);
				element.setOfficeStringValueAttribute(obj == null ? "" : obj.toString());
			}
			else
			{
				log.error(String.format("Brak gettera %s lub obiektu %s", fieldGetter.getName(),
						bean.toString()));
			}
		}
		catch (Exception e)
		{
			log.error(String.format("Blad w %s wywolania gettera pola %s obiektu %s", name,
					fieldGetter.getName(), bean.toString()));
			e.printStackTrace();
		}
	}
}
